package com.lw.leetcode.bit.b;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 1238. 循环码排列
 *
 * @author liw
 * @version 1.0
 * @date 2022/2/10 11:42
 */
public class CircularPermutation {

    public static void main(String[] args) {
        CircularPermutation test = new CircularPermutation();

        //
        int n = 3;
        int start = 2;

        List<Integer> list = test.circularPermutation(n, start);
        System.out.println(list);
    }

    public List<Integer> circularPermutation(int n, int start) {
        int length = 1 << n;
        int[] arr = new int[length];
        arr[0] = 1;
        arr[length - 1] = 0;
        int st = 1;
        int end = length - 2;
        int l = length >> 1;
        int item = 2;
        while (st < l) {
            for (int i = st - 1; i >= 0; i--) {
                arr[st++] = item + arr[i];
            }
            for (int i = end + 1; i < length; i++) {
                arr[end--] = item + arr[i];
            }
            item <<= 1;
        }

        List<Integer> list = new ArrayList<>(length);
        int index = 0;
        for (int i = 0; i < length; i++) {
            if (arr[i] == start) {
                index = i;
            }
        }
        for (int i = 0; i < length; i++) {
            index = index == length ? 0 : index;
            list.add(arr[index++]);
        }
        return list;
    }

}
